package com.azi.baseconhecimento.web;

import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.azi.baseconhecimento.entity.Comentario;
import com.azi.baseconhecimento.entity.Dica;
import com.azi.baseconhecimento.service.DicaService;
import com.azi.baseconhecimento.util.RequestCodeScape;

@Controller
public class DicaView {

	@Autowired
	private DicaService dicaService;

	
	@RequestMapping(value = "/dica/visualizar.htm", method = RequestMethod.GET)
	public ModelAndView init(ModelMap map, @RequestParam("id")
	Integer id) {
		Dica dica = dicaService.buscarDica(id);
		
		RequestCodeScape scape = new RequestCodeScape(dica.getDescricao());
		map.addAttribute("dica", dica);
		map.addAttribute("descricaoFormatada", scape.getCode());
		map.addAttribute("listFiles", scape.getListInports());
		
		return new ModelAndView("/dica/dicaView.jsp");
	}
	
	@RequestMapping(value = "/dica/salvarComentario.htm", method = RequestMethod.POST)
	public ModelAndView salvarComentario(ModelMap map, @RequestParam("id_dica")
	String idDica, @RequestParam("colaborador")
	String colaborador, @RequestParam("descricao")
	String descricao) {

		Dica dica = dicaService.buscarDica(Integer.parseInt(idDica));

		Comentario comentario = new Comentario();
		comentario.setColaborador(colaborador.trim());
		comentario.setDescricao(descricao);
		comentario.setDica(dica);
		comentario.setDataHora(new Date());

		if (dica.getComentarios() == null) {
			dica.setComentarios(new ArrayList<Comentario>());
		}

		dica.getComentarios().add(comentario);
		dica = dicaService.salvarDica(dica);
		
		map.addAttribute("dica", dica);
		
		return new ModelAndView("/dica/dicaView.jsp");
	}
	
}
